﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace KingsSharp.Core.Data.Entity.Migrations
{
    /// <summary>
    /// 在数据库不存在时使用种子数据创建数据库
    /// </summary>
    public class CreateDatabaseIfNotExistsWithSeed<TContext> : CreateDatabaseIfNotExists<TContext>
        where TContext:DbContext
    {
        static CreateDatabaseIfNotExistsWithSeed()
        {
            SeedActions = new Dictionary<Type, ICollection<ISeedAction>>();
        }

        /// <summary>
        /// 获取 数据库创建时的种子数据操作信息集合，各个模块可以添加自己的初始化数据
        /// </summary>
        public static Dictionary<Type,ICollection<ISeedAction>> SeedActions { get; private set; }

        /// <summary>
        /// 通过反射程序集获取种子数据库操作信息集合
        /// </summary>
        /// <param name="types"></param>
        /// <returns></returns>
        public static int SetSeedActionsType(Type contexttype,Type[] types)
        {
            if(!SeedActions.Any(a=>a.Key==contexttype))
            {
                SeedActions[contexttype] = new List<ISeedAction>();
            }
            foreach (var type in types)
            {
                SeedActions[contexttype].Add(Activator.CreateInstance(type) as ISeedAction);
            }
            return SeedActions.Count;
        }

        protected override void Seed(TContext context)
        {
            IEnumerable<ISeedAction> seedActions = SeedActions[typeof(TContext)].OrderBy(m => m.Order);
            foreach (ISeedAction seedAction in seedActions)
            {
                seedAction.Action(context);
            }
        }
    }
}